<template>
  <!-- SignUpInfoConfirm 报名信息确认 -->
  <PageContainer>
    <view class="container">
      <Header title="报名信息确认" />
      <BasicsForm @register="formRegister" @submit="onSubmit" />
    </view>
  </PageContainer>
</template>

<script lang="ts" setup>
  /**  SignUpInfoConfirm  报名信息确认 */
  import PageContainer from '@/components/PageContainer/index.vue';
  import Header from '@/components/Header/index.vue';
  import { navigateBack, onLoad, reLaunch, redirectTo } from '@/router';
  import BasicsForm from '@/components/Form/BasicsForm.vue';
  import { type FormSchema, useForm } from '@/components/Form';
  import { useUserStoreWithOut } from '@/store/modules/user';
  import { activityFormDetails, enterForActivity } from '@/api/activity';
  import { localDataMapping } from '@/components/Form/hooks/useForm';
  import { IsInternalInterfaceEnum, IsRequired } from '@/enums/formEnum';
  import { reactive, ref, unref } from 'vue';
  import { isArray } from '@/utils/is';
  import type { SignUpInfoConfirm } from '@/router/types/modules';
  import { ApprovalStatusEnum } from '@/enums/activityStatusEnum';
  import { authOfficialAccount } from '@/utils';
  import { memberTypeGetList } from '@/api/membership';
  import dictionary from '@/utils/dictionary';

  const useUser = useUserStoreWithOut();
  const userInfo = reactive({
    name: useUser.userInfo.name,
    phone: useUser.userInfo.phonenumber,
    companyName: useUser.userInfo.companyName,
    companyPosition: useUser.userInfo.companyPosition,
  });

  const schemas: FormSchema[] = [
    {
      field: 'basicInfo',
      label: '基本信息',
      component: 'Divider',
    },
    {
      field: 'name',
      label: '姓名',
      component: 'Input',
      required: true,
      componentProps: {
        maxlength: 12,
      },
    },
    {
      field: 'phone',
      label: '手机号码',
      component: 'InputPhone',
      required: true,
      dynamicDisabled: true,
    },
    {
      field: 'companyName',
      label: '单位名称',
      component: 'Input',
      required: true,
    },
    {
      field: 'companyPosition',
      label: '单位职务',
      component: 'Input',
      required: true,
    },
  ];

  interface dataListItem {
    type: string;
    field: string;
  }
  const typeDataName = ref<dataListItem[]>([]);
  const dictDataName = ref<dataListItem[]>([]);

  const [register, { appendSchemaByField, setFieldsValue, updateSchema }] = useForm({
    labelAlign: 'left',
    labelPosition: 'top',
    validateTrigger: 'bind',
    labelWidth: 'auto',
    btnGroupOptions: { submit: { text: '提交' } },
    // schemas: schemas,
  });

  let routeOptions: SignUpInfoConfirm;

  function formRegister(event: any) {
    register(event);

    getActivityFormItems();
  }

  function getActivityFormItems() {
    const { activityId } = routeOptions;
    activityFormDetails(activityId).then(async (r) => {
      const basicInfo = r.customFormItemMap[0] || [];
      const activityInfo = r.customFormItemMap[1] || [];
      if (basicInfo.length) {
        appendSchemaByField({
          field: 'basicInfo',
          label: '基本信息',
          component: 'Divider',
        });
        basicInfo.forEach((v) => {
          const field = v.id.toString();
          appendSchemaByField({
            field,
            label: v.showName,
            component: v.itemType,
            dataType: v.dataType,
            dynamicDisabled: v.disabled,
            defaultValue: v.itemDefault,
            required: v.isRequired === IsRequired.REQUIRED,
            componentProps: {
              placeholder: v.value,
              limit: v.length,
              itemDefault: v.itemDefault,
              enableValue: v.enableValue,
              localdata: localDataMapping(v.customFormItemAnswerList, {
                label: 'words',
                value: 'id',
              }),
            },
          });
        });
      }

      if (activityInfo.length) {
        appendSchemaByField({
          field: 'activityInfo',
          label: '活动信息收集',
          component: 'Divider',
        });
        activityInfo.forEach((v) => {
          const field = v.id.toString();
          if (v.isInternalInterface === IsInternalInterfaceEnum.CLASSIFICATION && v.type)
            typeDataName.value.push({ field, type: v.type });
          if (v.isInternalInterface === IsInternalInterfaceEnum.DICTIONARY && v.type)
            dictDataName.value.push({ field, type: v.type });
          appendSchemaByField({
            field,
            label: v.showName,
            component: v.itemType,
            dataType: v.dataType,
            dynamicDisabled: v.disabled,
            defaultValue: v.itemDefault,
            required: v.isRequired === IsRequired.REQUIRED,
            rulesMessageJoinLabel: false,
            isInternalInterface: v.isInternalInterface,
            ifShow(renderCallbackParams) {
              if (isArray(v.itemRelevanceAnsweIds)) {
                const values = renderCallbackParams.values;
                return Object.values(values).some((val) => {
                  return !!v.itemRelevanceAnsweIds?.find((id) => id == val);
                });
              }
              return true;
            },
            componentProps: {
              placeholder: v.value,
              limit: v.length,
              itemDefault: v.itemDefault,
              enableValue: v.enableValue,
              localdata: localDataMapping(v.customFormItemAnswerList, {
                label: 'words',
                value: 'id',
              }),
            },
          });
        });
      }
      await getLocaldata();
      setFieldsValue({
        personName: userInfo.name,
        personTel: userInfo.phone,
        companyName: userInfo.companyName,
        companyPosition: userInfo.companyPosition,
      });
    });
  }

  async function getLocaldata() {
    const td = typeDataName.value;
    const dd = dictDataName.value;
    if (td.length) {
      const res = await memberTypeGetList(td.map((v) => v.type));
      for (let index = 0; index < td.length; index++) {
        const item = td[index];
        updateSchema({
          field: item.field,
          componentProps: {
            localdata: localDataMapping(res[item.type], { label: 'name', value: 'id' }),
          },
        });
      }
    }
    if (dd.length) {
      const dictList = await dictionary.getMulti(dd.map((v) => v.type));
      for (let index = 0; index < dd.length; index++) {
        const item = dd[index];
        updateSchema({
          field: item.field,
          componentProps: {
            localdata: localDataMapping(dictList[item.type], {
              label: 'dictLabel',
              value: 'dictValue',
            }),
          },
        });
      }
    }
  }

  onLoad<'SignUpInfoConfirm'>((op) => {
    routeOptions = op;
    if (op.applicantInfo) {
      const { userName, phonenumber, companyName, companyPosition } = op.applicantInfo;
      userInfo.name = userName;
      userInfo.phone = phonenumber;
      userInfo.companyName = companyName;
      userInfo.companyPosition = companyPosition;
    }
  });

  const isApiLoading = ref(false);
  async function onSubmit(vals: Recordable) {
    if (unref(isApiLoading)) return;
    isApiLoading.value = true;
    const answerList: any[] = [];
    for (const key in vals) {
      let content = vals[key];
      if (!isArray(content)) content = content.toString().split(',');
      const answerItem = {
        formItemId: key,
        content,
      };
      answerList.push(answerItem);
    }
    if (!routeOptions) return;
    const customFormItem = answerList.length
      ? {
          answerList: answerList,
        }
      : void 0;
    /** 活动详情报名时 去授权公众号 */
    if (routeOptions.registerType === 'mini') {
      try {
        await authOfficialAccount();
      } catch (error) {}
    }
    enterForActivity({
      activityId: routeOptions.activityId,
      registerType: routeOptions.registerType,
      personTel: routeOptions.applicantInfo?.phonenumber,
      retinueId: routeOptions.applicantInfo?.retinueId,
      customFormItem,
    })
      .then(async (r) => {
        if (!useUser.cocInfo) {
          await useUser.setUserInfo();
        }
        if (
          routeOptions.registerType === 'mini_sign' &&
          r.approvalStatus === ApprovalStatusEnum.UNDERREVIEW
        ) {
          reLaunch({
            name: 'registrationUnderReview',
            options: {
              activityId: routeOptions.activityId,
              equipmentNumber: routeOptions.equipmentNumber,
            },
          });
        } else {
          routeOptions.success?.();
          if (routeOptions.registerType === 'mini_sign') {
            navigateBack();
          } else {
            redirectTo({ name: 'activityResult', options: {} });
          }
        }
      })
      .finally(() => (isApiLoading.value = false));
  }
</script>

<style lang="scss" scoped></style>
